<template>
    <div class="border-2 border-burlywood rounded-lg mb-5 mx-3 p-4">
        <div class="flex justify-start pb-8 overflow-x-auto">
            <div v-for="(tag, index) in tagsShow" :key="index" class="relative flex-none text-center w-20 h-20 my-2 ml-2 rounded-2xl bg-gray-400 border-4"
            :style="{borderColor: index % 2 === 0 ? '#c6e2ff' : '#f3d19e'}"
              @mouseenter="showInfo(index, true)" @mouseleave="showInfo(index, false)">
                <div class="relative w-16 h-16 ml-1 mt-1 rounded-full" :key="index" :style="{ backgroundColor: tag.color }">
                    <el-tag  v-if="index === (posReader[0]*2)" type="primary" class="absolute -bottom-9 -left-2">通道1读头</el-tag>
                    <el-tag  v-if="index === (posReader[1]*2+1)" type="warning" class="absolute -bottom-9 -left-2">通道2读头</el-tag>
                </div>
            </div>
        </div>
        <div class="mt-6 flex justify-between">
            <div class="flex-1 flex justify-center items-center flex-row">
                <el-button type="primary" :icon="ArrowLeft" @click="posChange(0,false)"></el-button>
                    <el-tag type="primary" size="large">通道1读头</el-tag>
                <el-button type="primary" :icon="ArrowRight" @click="posChange(0,true)"></el-button>
            </div>
            <div class="flex-1 flex justify-center items-center flex-row">
                <el-button type="warning" :icon="ArrowLeft" @click="posChange(1,false)"></el-button>
                <el-tag type="warning" size="large">通道2读头</el-tag>
                <el-button type="warning" :icon="ArrowRight" @click="posChange(1,true)"></el-button>
            </div>
        </div>

    </div>
    <div class="flex flex-col rounded-lg mx-3">
        <div class="flex justify-between">
            <div class="flex flex-col justify-start h-2/3 w-1/2 mb-1 pt-4 rounded-lg border-2 bg-gray-300">
                <el-text size="large"><el-icon> <Tickets /></el-icon> 通道1 </el-text>
                <div class="mt-4 h-[calc(60vh-200px)]">
                    <el-auto-resizer>
                        <template #default="{ height, width }">
                            <el-table-v2 :columns="columns" :data="table_data[0]" :height="height" :width="width" fixed>
                                <template #empty>
                                    <div class="empty">
                                        <!-- <el-empty /> -->
                                    </div>
                                </template>
                            </el-table-v2>
                        </template>
                    </el-auto-resizer>
                </div>
                <div class="flex flex-row justify-center items-center px-2 mt-4 mb-4"> 
                    <el-input v-model="channel_count[0].count" style="max-width: 140px"
                        :formatter="(value:number) => `总数: ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                    />
                    <el-input v-model="channel_count[0].ok" style="max-width: 130px"
                        :formatter="(value:number) => `OK: ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                    />
                    <el-input v-model="channel_count[0].ng" style="max-width: 100px"
                        :formatter="(value:number) => `NG: ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                    />
                    <el-input v-model="channel_count[0].rate" style="max-width: 70px"/>
                    <el-button type="danger" plain style="max-width: 30px" :icon="Refresh" @click="clean_count(0)"></el-button>
                </div>
            </div>
        <div class="flex flex-col justify-start h-90 w-1/2 mb-1 pt-4 rounded-lg border-2 bg-gray-300">
            <el-text size="large"><el-icon> <Tickets /></el-icon> 通道2</el-text>
            <div class="mt-4 h-[calc(60vh-200px)]">
                <el-auto-resizer>
                    <template #default="{ height,width }">
                        <el-table-v2 :columns="columns" :data="table_data[1]" :height="height" :width="width" fixed>
                            <template #empty>
                                <div class="empty">
                                    <!-- <el-empty /> -->
                                </div>
                            </template>
                        </el-table-v2>
                    </template>
                </el-auto-resizer>
            </div>
            <div class="flex flex-row justify-center items-center px-2 mt-4 mb-4"> 
                <el-input v-model="channel_count[1].count" style="max-width: 140px"
                    :formatter="(value:number) => `总数: ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                />
                <el-input v-model="channel_count[1].ok" style="max-width: 130px"
                    :formatter="(value:number) => `OK: ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                />
                <el-input v-model="channel_count[1].ng" style="max-width: 100px"
                    :formatter="(value:number) => `NG: ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                />
                <el-input v-model="channel_count[1].rate" style="max-width: 70px"/>
                <el-button type="danger" plain style="max-width: 30px" :icon="Refresh" @click="clean_count(1)"></el-button>
            </div>
        </div>
        </div>
        
        <div class="flex flex-row justify-center items-center px-2 mt-4 mb-4"> 
            <el-input v-model="count_total.count" style="max-width: 160px"
                :formatter="(value:number) => `总数: ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            />
            <el-input v-model="count_total.ok" style="max-width: 160px"
                :formatter="(value:number) => `OK: ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            />
            <el-input v-model="count_total.ng" style="max-width: 160px"
                :formatter="(value:number) => `NG: ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            />
            <el-input v-model="count_total.rate" style="max-width: 80px"/>
            <el-button type="danger" plain style="max-width: 160px" :icon="Refresh" @click="clean_count(2)">清除计数</el-button>
        </div>

    </div>

    <div class="flex fixed bottom-0 left-0 w-full h-auto text-sm bg-opacity-50 bg-white p-2 z-9999 select-none"> 
        <div class="text-sm text-gray-500 mr-2 w-1/3">
            {{ briefInfo.epc }}
        </div>
        <div class="text-sm text-gray-500 mr-2 w-1/3">
            {{ briefInfo.tid }}
        </div>
        <div class="text-sm text-gray-500 w-1/6">
            {{ briefInfo.rssi }}
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { listen } from '@tauri-apps/api/event'
import { Tickets,Refresh,ArrowLeft,ArrowRight} from '@element-plus/icons-vue';

interface Tag {
    epc: string;
    tid: string;
    rssi: number;
    state: number;
    detail:string;
    color: string;
}

interface TagInfo{
    id:number,
    tag: Tag,
}

interface Column{
    key:string,
    dataKey: string,
    title: string,
    width?:number
}

interface TableData{
    id:string,
    parentId: string|null,
    epc?: string,
    tid?: string,
    rssi?:number,
    state?:string,
    detail?:string
}

interface Channel{
    count:number,
    ng:number,
    ok:number,
    rate:string
}

const posReader = ref<[number,number]>([0,1]);
const briefShow = ref<{ index: number, enable: boolean}>({index:0,enable:false});


const tagsRaw = ref<[Tag[],Tag[]]>([[],[]])
const channel_count = ref<Channel[]>([{count:0,ng:0,ok:0,rate:"0"},{count:0,ng:0,ok:0,rate:"0"}])

const columns = ref<Column[]>(
    [
        {key:"id",dataKey:"id",title:"ID",width:60},
        {key:"epc",dataKey:"epc",title:"EPC",width:210},
        {key:"tid",dataKey:"tid",title:"TID",width:210},
        {key:"rssi",dataKey:"rssi",title:"Rssi",width:50},
        {key:"state",dataKey:"state",title:"State",width:50},
        {key:"detail",dataKey:"detail",title:"Detail",width:210},
    ]
);


const table_data = ref<[TableData[],TableData[]]>([[],[]])
const count = ref<number>(0)

onMounted(() => {
    startFlow();
});

const startFlow = async () => {
    await listen<TagInfo>('tags_receive', (event) => {
        count.value++;
        const {id, tag } = event.payload as TagInfo;

        if (tag.state == 1){
            channel_count.value[id].ok++;
        }else{
            channel_count.value[id].ng++;
        }

        channel_count.value[id].count = channel_count.value[id].ng + channel_count.value[id].ok;
        channel_count.value[id].rate = (100 * channel_count.value[id].ok / channel_count.value[id].count).toFixed(2)+"%";

        if (tagsRaw.value[id].length > 15){
            tagsRaw.value[id].pop()
        }
        tagsRaw.value[id].unshift(tag);

        table_data.value[id].push({
            id: `${count.value}`,
            parentId: null,
            epc:tag.epc,
            tid:tag.tid,
            rssi:tag.rssi,
            state:(tag.state === 1) ? "OK" : "NG",
            detail:tag.detail,
        });
        if (table_data.value[id].length>100){
            table_data.value[id].shift()
        }
    })
}

function clean_count(index:number){
    if (index == 0 || index ==1) {
        channel_count.value[index]={count:0,ng:0,ok:0,rate:"0"};
    }
    else{
        channel_count.value[0]={count:0,ng:0,ok:0,rate:"0"};
        channel_count.value[1]={count:0,ng:0,ok:0,rate:"0"};
    }
}

const posChange = ( pos: number, shift: boolean) => {
    if(shift){
        posReader.value[pos] = posReader.value[pos]+1;
    }else{
        posReader.value[pos] = posReader.value[pos]-1;
    }
    if(posReader.value[pos] < 0){
        posReader.value[pos] = 0;
    }
    if(posReader.value[pos] > 9){
        posReader.value[pos] = 9;
    }
};

const showInfo = ( index: number, enable: boolean) => {
    briefShow.value.index = index;
    briefShow.value.enable = enable;
};

const briefInfo = computed(() => {
  // 检查是否启用以及索引是否有效
  const index = briefShow.value.index;
  if (!briefShow.value.enable || index === null || !tagsShow.value || !tagsShow.value[index]) {
    return { epc: '', tid: '', rssi: '' };
  }
  const tag_info = tagsShow.value[index];
  return {
    epc: "EPC:" + tag_info.epc,
    tid: "TID:" + tag_info.tid,
    rssi:"RSSI:" + tag_info.rssi.toString() // 确保 rssi 是字符串
  };
});

const tagsShow =  computed(() => {
    const defaultTag = { epc: '', tid: '', rssi: 0, color: 'grey', state: 1 };
    const tags_base_1 = Array.from({ length: posReader.value[0] }, () => defaultTag);
    const tags_base_2 = Array.from({ length: posReader.value[1] }, () => defaultTag);

    tags_base_1.push(...tagsRaw.value[0]);
    tags_base_2.push(...tagsRaw.value[1]);

    const combinedArray = [];
    const maxLength = Math.max(tags_base_1.length, tags_base_2.length);
    for (let i = 0; i < maxLength; i++) {
    const tag1 = tags_base_1[i] || defaultTag;
    const tag2 = tags_base_2[i] || defaultTag;
    combinedArray.push(tag1, tag2);
    }

    return combinedArray;
});

const count_total = computed(()=>{
    const count = {count:0,ng:0,ok:0,rate:"0"}
    count.ok = channel_count.value[0].ok + channel_count.value[1].ok;
    count.ng = channel_count.value[0].ng + channel_count.value[1].ng;
    count.count = count.ng + count.ok;
    count.rate = (100 * count.ok / count.count).toFixed(2)+"%";
    return count;
})
</script>

<style scoped>
.empty {
  background-color: aqua;
}
</style>